package command

import (
	"context"
	"gitee.com/bei_yi_ning/gorder/common/logging"

	"gitee.com/bei_yi_ning/gorder/common/decorator"
	domain "gitee.com/bei_yi_ning/gorder/order/domain/order"
	"github.com/sirupsen/logrus"
)

type UpdateOrder struct {
	Order    *domain.Order
	UpdateFn func(ctx context.Context, o *domain.Order) (*domain.Order, error)
}

type UpdateOrderHandler decorator.CommandHandler[UpdateOrder, any]

type updateOrderHandler struct {
	orderRepo domain.Repository
	//stockGRPC
}

func NewUpdateOrderHandler(orderRepo domain.Repository, logger *logrus.Logger, metricClient decorator.MetricsClient) UpdateOrderHandler {
	if orderRepo == nil {
		panic("orderRepo is nil")
	}
	return decorator.ApplyCommandDecorators[UpdateOrder, any](
		updateOrderHandler{orderRepo: orderRepo},
		logger,
		metricClient)
}

func (u updateOrderHandler) Handle(ctx context.Context, cmd UpdateOrder) (any, error) {
	var err error
	defer logging.WhenCommandExecute(ctx, "UpdateOrderHandler", cmd, err)
	if cmd.UpdateFn == nil {
		logrus.Panicf("UpdateOrderHandler got nil cmd.UpdateFn , cmd=%+v ", cmd)
	}
	if err = u.orderRepo.Update(ctx, cmd.Order, cmd.UpdateFn); err != nil {
		return nil, err
	}
	return nil, nil
}
